<template>
    <div>
        <div class="flex items-center">
            <div class="bg-primary w-60px h-32px bg-opacity-10 rounded-4px cursor-pointer overflow-hidden relative">
                <div class="text-primary flex items-center px-6px">
                    <img class="w-16px h-16px" src="../../assets/image/membership/icon-upload.png" alt="">
                    <div>
                        上传
                    </div>
                </div>
                <input ref="inputRef" :multiple="item.extra?.multiple ?? false" :accept="accepts"
                    class="absolute cursor-pointer left-0 top-0 w-full h-full opacity-0" type="file" @change="onChange">
            </div>
            <div class="text-sm text-lightgray ml-4px">{{ item.extra?.hint ?? '' }}</div>
        </div>

        <div class="flex justify-between items-center mt-10px" v-for="(i, index) in fileList" :key="index">
            <div class="flex-1">
                <div class="break-all text-base text-primary">{{ i.name }}</div>
            </div>
            <div class="w-16px flex-shrink-0 ml-6px hover:text-primary" @click="onRemoveFile(index)">
                <el-icon class="cursor-pointer" size="20px">
                    <Close />
                </el-icon>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import type { PropType } from 'vue'
import type { FormItemDto } from '@/components/form-component/type'

const props = defineProps({
    value: {
        type: Array,
        default() {
            return []
        }
    },
    item: {
        type: Object as PropType<FormItemDto>,
        required: true
    },
    // hint: {
    //     type: String,
    //     default: 'png、gif格式，小于1M'
    // },
    // accept: {
    //     type: Array,
    //     default() {
    //         return ['.png', '.gif']
    //     }
    // },
    // multiple: {
    //     type: Boolean,
    //     default: false
    // },
    // limitSize: {
    //     type: Number,
    //     default: 0
    // },
    // widthbase64Head: {
    //     type: Boolean,
    //     default: false
    // }
})

const emits = defineEmits(['update:value'])

const acceptList = computed(() => {
    const defaultAcctpt = ['.png', '.gif']
    return props.item?.extra?.accept ?? defaultAcctpt
})

const accepts = computed(() => {
    return acceptList.value.join(',')
})

const inputRef = ref()
const fileList = ref<File[]>([] as File[])

const onChange = (ev: Event) => {
    const { files } = ev.target as HTMLInputElement
    if (!files) return
    const typeList = Array.from(files)?.map((i: File) => i.type.split('/')[1])
    if (typeList.some(i => !acceptList.value.includes('.' + i))) {
        ElMessage.error(`请上传类型为${accepts.value}的文件`)
        handleClearValue()
        return
    }

    if ((props.item?.extra?.limit as number) > 0 && files.length > (props.item?.extra?.limit as number)) {
        ElMessage.error(`最多只能上传${props.item?.extra?.limit}个文件`)
        handleClearValue()
        return
    }

    if (props.item?.extra?.limitSize) {
        if (Array.from(files).some(i => i.size / 1024 / 1024 > (props.item?.extra?.limitSize as number))) {
            ElMessage.error(`请上传小于${props.item?.extra?.limitSize}M的文件`)
            handleClearValue()
            return
        }
    }
    fileList.value = Array.from(files)
}

const handleClearValue = () => {
    if (inputRef.value) {
        inputRef.value.value = null
    }
}

const onRemoveFile = (index: number) => {
    fileList.value.splice(index, 1)
    emits('update:value', fileList.value?.length ? fileList.value : null)
    handleClearValue()
}

const fileToBase64 = (files: File) => {
    return new Promise((resolve, reject) => {
        const fileReader = new FileReader()
        fileReader.readAsDataURL(files)
        fileReader.onload = () => {
            console.log(fileReader.result)
            if (!props.item?.extra?.withBase64Head) {
                resolve('base64' + fileReader.result?.toString().split('base64')[1])
            }
            resolve(fileReader.result)
        }
        fileReader.onerror = (error) => {
            reject(error)
        }
    })
}

const batchFileToBase64 = async (files: File[]) => {
    const allPromise = [] as Promise<Awaited<ReturnType<typeof fileToBase64>>>[]
    files.forEach(async (i: File) => {
        allPromise.push(fileToBase64(i))
    })
    return Promise.all(allPromise)
}

watch(fileList, async (newval: File[]) => {
    if (newval.length) {
        const res = await batchFileToBase64(newval)
        emits('update:value', res)
    } else {
        emits('update:value', null)
    }
})

</script>
<style lang="scss" scoped></style>
